import React, { PureComponent,Fragment } from 'react';
import { notification, Icon, Tree, Modal } from 'antd';
import { connect } from 'dva';
import "./index.less"
import ToolConfigModals from '../../components/toolConfigModals';
import PileCrossSection from "../../components/forms/pileCrossSection"
import FoundCrossSection from "../../components/forms/foundCrossSection"
import PileFoundCrossSection from "../../components/forms/pileFoundCrossSection"
import { cloneDeep } from "lodash"
import {bus} from "../../utils/bus"
const { TreeNode } = Tree;
class Renforce extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            tindex: 0,
            loading: false,
            mode: "add",
            checkedAll: true,
            nodeId: 11,
            situation: "pileCrossSection",
            loadedKeys: [],
            expandedKeys: [],
            autoExpandParent: false,
            tabs: [{ id: "1", key: "crossSection", title: "配筋", children: [{ id: "11", key: "pileCrossSection", title: "承台配筋", selected: true }, { id: "12", key: "pileFoundCrossSection", title: "桩基配筋", }, { id: "13", key: "foundCrossSection", title: "垫石配筋", }] }],
            created: false,
        }
        this.submit = this.submit.bind(this)
        this.tabChange = this.tabChange.bind(this)
        this.renderTreeNodes = this.renderTreeNodes.bind(this)
        this.getTargetNodes = this.getTargetNodes.bind(this)
        this.insertTreeNode = this.insertTreeNode.bind(this)
        this.removeTreeNode = this.removeTreeNode.bind(this)
        this.getTreeNode = this.getTreeNode.bind(this)
        this.updateTreeNode = this.updateTreeNode.bind(this)
        this.onSelect = this.onSelect.bind(this)
        this.loadData = this.loadData.bind(this)
        this.onExpand = this.onExpand.bind(this)
        this.loopTreeNode = this.loopTreeNode.bind(this)
        this.deleteNodeData = this.deleteNodeData.bind(this)
        this.export = this.export.bind(this)
        this.getNameBySitua = this.getNameBySitua.bind(this)
        this.setCrossDefault=this.setCrossDefault.bind(this)
        this.getGjsn=this.getGjsn.bind(this)
        this.validate=this.validate.bind(this)
    }
    validate(str) {
        let reg = true;
        str=str.replace(/\uff0c/g,",")
        str=str.replace(/\s/g, "")
        if (str.includes(",")) {
            let arr = str.split(",");
            const len = arr.length;
            for (let i = 0; i < len; i++) {
                let item = arr[i];
                try {
                    eval(item)
                } catch (error) {
                    reg = false
                }
            }
        } else {
            reg = false
        }
        return reg;
    }
    deleteNodeData(e, item) {
        e.preventDefault();
        e.stopPropagation()
        Modal.confirm({
            title: "提示",
            content: "是否删除当前节点?",
            okText: "确定",
            cancelText: "取消",
            onOk: () => {
                if (item.key.includes("pileCrossSectionUnit")) {
                    const id = item.key.replace(/pileCrossSectionUnit/g, '')
                    this.props.deleteCapReinforcement({ ids: [Number(id)] }, res => {
                        this.removeTreeNode(item.key)
                        this.setState({
                            detail: null,
                            updateTime: null,
                            tdata: null,
                            reinforcementDetailSummary: null,
                            singleMaterialSummary: null,
                            materialSummary: null
                        })
                    }, err => {

                    })
                } else if (item.key.includes("foundCrossSectionUnit")) {
                    const id = item.key.replace(/foundCrossSectionUnit/g, '')
                    this.props.deleteCushionStone({ ids: [Number(id)] }, res => {
                        this.removeTreeNode(item.key)
                        this.setState({
                            detail: null,
                            updateTime: null,
                            tdata: null,
                            reinforcementDetailSummary: null,
                            singleMaterialSummary: null,
                            materialSummary: null
                        })
                    }, err => {

                    })
                } else if (item.key.includes("pileFoundCrossSectionUnit")) {
                    const id = item.key.replace(/pileFoundCrossSectionUnit/g, '')
                    this.props.deletePileReinforcement({ ids: [Number(id)] }, res => {
                        this.removeTreeNode(item.key)
                        this.setState({
                            detail: null,
                            updateTime: null,
                            tdata: null,
                            reinforcementDetailSummary: null,
                            singleMaterialSummary: null,
                            materialSummary: null
                        })
                    }, err => {

                    })

                }
            },
            onCancel: () => {

            }
        })

    }
    async setCrossDefault(){
        const {situation}=this.state;
        let code;
        if(situation=="pileCrossSection"){
            code="CAP"
        }else if(situation=="foundCrossSection"){
            code="CUSHION_STONE"
        }else if(situation=="pileFoundCrossSection"){
            code="PILE"
        }
        
        let res=await this.props.crossTempList({code})
        let tempFir=res&&res.length?res[0]:null;
        let arrrs=tempFir?tempFir.crossSectionTemplateGeoAttrs:[]
        let obj={crossSection:tempFir?tempFir.name:"",value:tempFir?tempFir.id:null,code}
        obj.temp=tempFir;
        obj.crossSection = tempFir.name;
        obj.cid=tempFir.id;
        if(arrrs&&arrrs.length){
            const len=arrrs.length;
            for (let i = 0; i < len; i++) {
                let item = arrrs[i];
                obj[item.keyName]=item.defaultValue/10||""
            }
            bus.emit("crossSectionFinish",obj)
        }
    }
    getTreeNode(data, key) {
        let obj;
        function getOneTarget(data, key) {
            if (data && data.length) {
                const len = data.length;
                for (let i = 0; i < len; i++) {
                    let item = data[i];
                    item.selected = false
                    if (item && item.id == key) {
                        obj = item;
                    } else {
                        if (item && item.children && item.children.length) {
                            getOneTarget(item.children, key)
                        }
                    }
                }
            }
            return obj;
        }
        return getOneTarget(data, key)
    }
    getTargetNodes(data, key, remove) {//数组|字符串,remove控制删除
        let target;
        let isArray = key instanceof Array;
        let targets = []
        function oneTarget(list) {
            const len = list.length;
            for (let i = 0; i < len; i++) {
                let item = list[i];
                if (!isArray) {
                    if (item && item.key == key) {
                        target = item;
                        if (remove) {
                            list.splice(i, 1)
                        }
                        break;
                    } else {
                        if (item && item.children && item.children.length) {
                            oneTarget(item.children)
                        }
                    }
                } else {
                    if (key && key.length) {
                        const len2 = key.length
                        for (let j = 0; j < len2; j++) {
                            const item2 = key[j];
                            if (item && item.key == item2) {
                                targets.push(item);
                                if (remove) {
                                    list.splice(i, 1)
                                }
                                break;
                            } else {
                                if (item && item.children && item.children.length) {
                                    oneTarget(item.children)
                                }
                            }
                        }
                    }
                }

            }
            return isArray ? targets : target
        }
        return oneTarget(data)
    }
    removeTreeNode(keys) {
        let data = this.state.tabs;
        if (keys) {
            let res = this.getTargetNodes(data, keys, true)
            this.setState({
                tabs: [...this.state.tabs]
            })
        }

    }
    insertTreeNode(key, obj) {//单个|多个节点插入
        let data = this.state.tabs;
        let target = this.getTargetNodes(data, key)
        let isArray = target instanceof Array;
        let isArray2 = obj instanceof Array;
        if (!isArray) {
            if (target) {
                if (target.children && target.children.length) {
                    if (!isArray2) {
                        if (!target.children.find(item => item && item.key == obj.key)) {
                            target.children.push(obj)
                        }
                    } else {
                        if (obj && obj.length) {
                            const len = obj.length;
                            for (let i = 0; i < len; i++) {
                                let item = obj[i];
                                if (!target.children.find(item2 => item2 && item2.key == item.key)) {
                                    target.children.push(item)

                                }
                            }
                        }
                    }
                } else {
                    target.children = !isArray2 ? [obj] : obj
                }


            }
        } else {
            if (target && target.length) {
                for (let i = 0; i < target.length; i++) {
                    let item = target[i];
                    if (item.children && item.children.length) {
                        if (!isArray2) {
                            if (!item.children.find(item2 => item2 && item2.key == item.key)) {
                                item.children.push(obj)
                            }
                        } else {
                            if (obj && obj.length) {
                                for (let j = 0; j < obj.length; j++) {
                                    let item2 = obj[j];
                                    if (!item.children.find(item3 => item3 && item3.key == item2.key)) {
                                        item.children.push(item2)
                                    }
                                }
                            }
                        }
                    } else {
                        item.children = !isArray2 ? [obj] : obj
                    }

                }
            }
        }
        // this.setState({
        //     tabs: [...data]
        // })
    }
    submit(e) {
        e.preventDefault();
        e.stopPropagation();
        const { situation, mode,formContext } = this.state;
        let list = document.querySelectorAll("form .input")
        let obj = {}
        const len = list.length;
        this.setState({
            loading: true,
            created: true,
            detail: null,
            updateTime: null,
        })
        for (let i = 0; i < len; i++) {
            let node = list[i];
            node.value=node.value.replace(/\uff0c/g,",")
            node.value=node.value.replace(/\s/g, "")
            node.classList.remove("required")
            if (node.disabled) {
                continue;
            }
            if (!node.value) {
                this.setState({
                    loading: false,
                })
                node.classList.add("required")
                node.focus()
                notification.warn({ message: `请将${node.name}字段填写完整` })
                node.scrollIntoView({

                    block: 'start', behavior: 'auto'
            
                  });
                // document.querySelector(".tableBox").scrollTop= node.offsetTop+node.parentNode.parentNode.scrollHeight
               
                return;
            }
            if(node.dataset.handler){
                if(String(node.value).includes("*")){
                    obj[node.dataset.key]=node.value.split("*").map(item=>item*10).join("*")
                }else if(String(node.value).includes(",")){
                    obj[node.dataset.key]=node.value.split(",").map(item=>item*10).join(",")
                }else{
                    obj[node.dataset.key]=eval(node.value+node.dataset.handler)
                   
                }
               
            }else{
                obj[node.dataset.key] = node.value
            }
            if(node.dataset.validate){
                if (!this[node.dataset.validate](node.value)) {
                    this.setState({
                        loading: false,
                    })
                    node.classList.add("required")
                    node.focus()
                    notification.warn({ message: `${node.dataset.name}字段格式不正确!` })
                    document.querySelector(".tableBox").scrollTop=node.offsetTop+node.parentNode.parentNode.scrollHeight
                    return;
                }
            }
            const arr=node.value.replace(/\uff0c/g,",").split(",")
            if(node.dataset.key=="topSize"){
                if(arr.length=0||arr.length>2||arr.some(item=>typeof(item-0)!="number")){
                    node.classList.add("required")
                    node.focus()
                    notification.warn({ message: `${node.name}字段不正确` })
                    document.querySelector(".tableBox").scrollTop=node.offsetTop+node.parentNode.parentNode.scrollHeight
                    this.setState({
                        loading: false,
                    })
                    return;
                }
            }else if(node.dataset.key=="bottomSize"){
                if(arr.length=0||arr.length>2||arr.some(item=>typeof(item-0)!="number")){
                    this.setState({
                        loading: false,
                    })
                    node.classList.add("required")
                    node.focus()
                    notification.warn({ message: `${node.name}字段不正确` })
                    document.querySelector(".tableBox").scrollTop=node.offsetTop+node.parentNode.parentNode.scrollHeight
                    
                    return;
                }
            }
           
        }
        obj.projectId = this.props.project.id;
        obj.crossSectionTemplateVo=formContext.state.extra.temp
        obj.templateId=formContext.state.extra.temp.id
        return new Promise((resolve, reject) => {
            if (situation == "pileCrossSection") {
                if (mode == "add") {
                    this.props.addCapReinforcement(obj, res => {
                        const len = res.data.data.singleMaterialSummary.length;
                        const len2 = res.data.data.materialSummary.length;
                        for (let i = 0; i < len; i++) {
                            let item = res.data.data.singleMaterialSummary[i];
                            if (!item.mergeSize) {
                                if (i > 0 && res.data.data.singleMaterialSummary[i].type == res.data.data.singleMaterialSummary[i - 1].type) {
                                    item.merged = true
                                }
                            }
                        }
                        for (let i = 0; i < len2; i++) {
                            let item = res.data.data.materialSummary[i];
                            if (!item.mergeSize) {
                                if (i > 0 && res.data.data.materialSummary[i].type == res.data.data.materialSummary[i - 1].type) {
                                    item.merged = true
                                }
                            }
                        }
                        let unit = cloneDeep(res.data.data.capReinforcement);
                        unit.key = "pileCrossSectionUnit" + unit.id;
                        unit.title = "方案:" + unit.configureName;

                        unit.isLeaf = true
                        if (unit.isLeaf) {
                            unit.title = <span>{unit.title}&nbsp;&nbsp;<Icon onClick={e => this.deleteNodeData(e, unit)} type="delete" /></span>
                        }
                        this.insertTreeNode("pileCrossSection", unit)
                        this.setState({
                            updateTime: new Date(res.data.data.capReinforcement.updateTime).toLocaleDateString(),
                            crossSectionTemplate:res.data.data.crossSectionTemplate,
                            tdata: res.data.data.reinforcementDetail,
                            selectedKeys: [unit.key],
                            detail: unit,
                            reinforcementDetailSummary: res.data.data.reinforcementDetailSummary,
                            singleMaterialSummary: res.data.data.singleMaterialSummary,
                            materialSummary: res.data.data.materialSummary
                        })

                        resolve(res)
                    }, err => {
                        reject(err)
                    })
                } else {
                    this.props.updateCapReinforcement(obj, res => {
                        const len = res.data.data.singleMaterialSummary.length;
                        const len2 = res.data.data.materialSummary.length;
                        for (let i = 0; i < len; i++) {
                            let item = res.data.data.singleMaterialSummary[i];
                            if (!item.mergeSize) {
                                if (i > 0 && res.data.data.singleMaterialSummary[i].type == res.data.data.singleMaterialSummary[i - 1].type) {
                                    item.merged = true
                                }
                            }
                        }
                        for (let i = 0; i < len2; i++) {
                            let item = res.data.data.materialSummary[i];
                            if (!item.mergeSize) {
                                if (i > 0 && res.data.data.materialSummary[i].type == res.data.data.materialSummary[i - 1].type) {
                                    item.merged = true
                                }
                            }
                        }
                
                        this.setState({
                            updateTime: new Date(res.data.data.capReinforcement.updateTime).toLocaleDateString(),
                            crossSectionTemplate:res.data.data.crossSectionTemplate,
                            tdata: res.data.data.reinforcementDetail,
                            selectedKeys: ["pileCrossSectionUnit" + obj.id],
                            detail: res.data.data.capReinforcement,
                            reinforcementDetailSummary: res.data.data.reinforcementDetailSummary,
                            singleMaterialSummary: res.data.data.singleMaterialSummary,
                            materialSummary: res.data.data.materialSummary
                        })
                        resolve(res)
                    }, err => {
                        reject(err)
                    })

                }

            } else if (situation == "foundCrossSection") {
                if (mode == "add") {
                    this.props.addCushionStone(obj, res => {
                        const len = res.data.data.singleMaterialSummary.length;
                        const len2 = res.data.data.materialSummary.length;
                        for (let i = 0; i < len; i++) {
                            let item = res.data.data.singleMaterialSummary[i];
                            if (!item.mergeSize) {
                                if (i > 0 && res.data.data.singleMaterialSummary[i].type == res.data.data.singleMaterialSummary[i - 1].type) {
                                    item.merged = true
                                }
                            }
                        }
                        for (let i = 0; i < len2; i++) {
                            let item = res.data.data.materialSummary[i];
                            if (!item.mergeSize) {
                                if (i > 0 && res.data.data.materialSummary[i].type == res.data.data.materialSummary[i - 1].type) {
                                    item.merged = true
                                }
                            }
                        }
                        let unit = cloneDeep(res.data.data.cushionStone)
                        unit.key = "foundCrossSectionUnit" + unit.id;
                        unit.title = "方案:" + unit.configureName;
                        unit.isLeaf = true;
                        if (unit.isLeaf) {
                            unit.title = <span>{unit.title}&nbsp;&nbsp;<Icon onClick={e => this.deleteNodeData(e, unit)} type="delete" /></span>
                        }
                        this.insertTreeNode("foundCrossSection", unit)
                        this.setState({
                            updateTime: new Date(res.data.data.cushionStone.updateTime).toLocaleDateString(),
                            crossSectionTemplate:res.data.data.crossSectionTemplate,
                            tdata: res.data.data.reinforcementDetail,
                            selectedKeys: ["foundCrossSectionUnit" + unit.id],
                            detail: res.data.data.cushionStone,
                            reinforcementDetailSummary: res.data.data.reinforcementDetailSummary,
                            singleMaterialSummary: res.data.data.singleMaterialSummary,
                            materialSummary: res.data.data.materialSummary
                        })
                        resolve(res)
                    }, err => {
                        reject(err)
                    })
                } else {

                    this.props.updateCushionStone(obj, res => {

                        const len = res.data.data.singleMaterialSummary.length;
                        const len2 = res.data.data.materialSummary.length;
                        for (let i = 0; i < len; i++) {
                            let item = res.data.data.singleMaterialSummary[i];
                            if (!item.mergeSize) {
                                if (i > 0 && res.data.data.singleMaterialSummary[i].type == res.data.data.singleMaterialSummary[i - 1].type) {
                                    item.merged = true
                                }
                            }
                        }
                        for (let i = 0; i < len2; i++) {
                            let item = res.data.data.materialSummary[i];
                            if (!item.mergeSize) {
                                if (i > 0 && res.data.data.materialSummary[i].type == res.data.data.materialSummary[i - 1].type) {
                                    item.merged = true
                                }
                            }
                        }
                        this.setState({
                            updateTime: new Date(res.data.data.cushionStone.updateTime).toLocaleDateString(),
                            crossSectionTemplate:res.data.data.crossSectionTemplate,
                            tdata: res.data.data.reinforcementDetail,
                            selectedKeys: ["foundCrossSectionUnit" + obj.id],
                            detail: res.data.data.cushionStone,
                            reinforcementDetailSummary: res.data.data.reinforcementDetailSummary,
                            singleMaterialSummary: res.data.data.singleMaterialSummary,
                            materialSummary: res.data.data.materialSummary
                        })
                        resolve(res)
                    }, err => {

                        reject(err)
                    })
                }

            } else if (situation == "pileFoundCrossSection") {
                if (mode == "add") {
                    this.props.addPileReinforcement(obj, res => {
                        const len = res.data.data.singleMaterialSummary.length;
                        const len2 = res.data.data.materialSummary.length;
                        for (let i = 0; i < len; i++) {
                            let item = res.data.data.singleMaterialSummary[i];
                            if (!item.mergeSize) {
                                if (i > 0 && res.data.data.singleMaterialSummary[i].type == res.data.data.singleMaterialSummary[i - 1].type) {
                                    item.merged = true
                                }
                            }
                        }
                        for (let i = 0; i < len2; i++) {
                            let item = res.data.data.materialSummary[i];
                            if (!item.mergeSize) {
                                if (i > 0 && res.data.data.materialSummary[i].type == res.data.data.materialSummary[i - 1].type) {
                                    item.merged = true
                                }
                            }
                        }
                        let unit = cloneDeep(res.data.data.pileReinforcement)
                        unit.key = "pileFoundCrossSectionUnit" + unit.id;
                        unit.title = "方案:" + unit.configureName;
                        unit.isLeaf = true;
                        if (unit.isLeaf) {
                            unit.title = <span>{unit.title}&nbsp;&nbsp;<Icon onClick={e => this.deleteNodeData(e, unit)} type="delete" /></span>
                        }
                        this.insertTreeNode("pileFoundCrossSection", unit)
                        this.setState({
                            updateTime: new Date(res.data.data.pileReinforcement.updateTime).toLocaleDateString(),
                            crossSectionTemplate:res.data.data.crossSectionTemplate,
                            tdata: res.data.data.reinforcementDetail,
                            selectedKeys: ["pileFoundCrossSectionUnit" + unit.id],
                            detail: res.data.data.pileReinforcement,
                            reinforcementDetailSummary: res.data.data.reinforcementDetailSummary,
                            singleMaterialSummary: res.data.data.singleMaterialSummary,
                            materialSummary: res.data.data.materialSummary
                        })
                        resolve(res)
                    }, err => {
                        reject(err)
                    })
                } else {

                    this.props.updatePileReinforcement(obj, res => {

                        const len = res.data.data.singleMaterialSummary.length;
                        const len2 = res.data.data.materialSummary.length;
                        for (let i = 0; i < len; i++) {
                            let item = res.data.data.singleMaterialSummary[i];
                            if (!item.mergeSize) {
                                if (i > 0 && res.data.data.singleMaterialSummary[i].type == res.data.data.singleMaterialSummary[i - 1].type) {
                                    item.merged = true
                                }
                            }
                        }
                        for (let i = 0; i < len2; i++) {
                            let item = res.data.data.materialSummary[i];
                            if (!item.mergeSize) {
                                if (i > 0 && res.data.data.materialSummary[i].type == res.data.data.materialSummary[i - 1].type) {
                                    item.merged = true
                                }
                            }
                        }
                        this.setState({
                            updateTime: new Date(res.data.data.pileReinforcement.updateTime).toLocaleDateString(),
                            crossSectionTemplate:res.data.data.crossSectionTemplate,
                            tdata: res.data.data.reinforcementDetail,
                            selectedKeys: ["pileFoundCrossSectionUnit" + obj.id],
                            detail: res.data.data.pileReinforcement,
                            reinforcementDetailSummary: res.data.data.reinforcementDetailSummary,
                            singleMaterialSummary: res.data.data.singleMaterialSummary,
                            materialSummary: res.data.data.materialSummary
                        })
                        resolve(res)
                    }, err => {

                        reject(err)
                    })
                }
            }
            this.setState({
                loading: false
            })

        })

    }
    componentWillUnmount() {
        sessionStorage.setItem("hisPre", this.props.location.pathname)
    }
    async componentDidMount() {
        if (!sessionStorage.getItem("isLogin")) {
            this.props.history.push("/login")
            return;
        }
        const { tabs } = this.state;
        const expandedKeys = tabs.map(item => item.key)
        this.setState({
            expandedKeys
        })
        this.setCrossDefault()


    }
    export() {
        const { detail, situation } = this.state;
        if (!detail) {
            notification.warn({ message: "请选择方案!" })
            return;
        }
        const index = ["pileCrossSection", "pileFoundCrossSection", "foundCrossSection"].findIndex(item => item == situation) + 1
        this.props.exportCapReinforcement({ id: detail.id, type: index }, res => {
            let a = document.createElement("a")
            a.style.display = 'none';
            a.target = "_blank"
            a.download = `${detail.configureName}配筋方案.xlsx`
            const blobData = new Blob([res], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8" })
            const url = URL.createObjectURL(blobData)
            a.href = url
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
        }, err => {

        })

    }
    renderTreeNodes(data) {
        return data.map(item => {
            if (item.children && !item.hidden) {
                return (
                    <TreeNode checkable={item.checkable} title={item.title} key={item.key} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            return !item.hidden ? <TreeNode checkable={item.checkable} title={item.title} key={item.key} {...item} dataRef={item}></TreeNode> : undefined;

        });
    }
    tabChange(e, index) {
        e.preventDefault();

        this.setState({
            tindex: index
        })
    }
    onExpand(expandedKeys) {
        this.setState({
            expandedKeys: expandedKeys,
            autoExpandParent: false,
        })
    }
    loopTreeNode(data) {
        let _this = this;
        function loop(list) {
            if (list && list.length) {
                const len = list.length;
                for (let i = 0; i < len; i++) {
                    let item = list[i]
                    if (item.isLeaf) {
                        item.title = <span>{item.title}<Icon onClick={e => this.deleteNodeData(e, item)} type="delete" /></span>
                    }

                    if (item && item.children && item.children.length) {
                        loop(item.children)
                    } else {
                        continue;
                    }
                }

            }
            return list;
        }
        return loop(data)
    }
    getNameBySitua() {
        const { situation } = this.state;
        let name = ""
        switch (situation) {
            case "pileCrossSection":
                name = "承台"
                break;
            case "foundCrossSection":
                name = "垫石"
                break;
            case "pileFoundCrossSection":
                name = "桩基"
                break;
            default:
                break;
        }
        return name;
    }
    async onSelect(keys, e) {
        let dataRef = e.node.props.dataRef
        const {situation}=this.state;
        let eventType;
        if (dataRef) {
            eventType = dataRef.key
        } else {
            dataRef = e.node.props
            eventType = dataRef.eventKey
        }
        // if (this.state.formContext) {
        //     this.state.formContext.clearFormData()
        // }
        await this.setState({
            crossSectionTemplate:null,
            situation:null,
            loading: true,
            selectedKeys: keys,
            detail: null,
            updateTime: null,
            tdata: null,
            reinforcementDetailSummary: null,
            singleMaterialSummary: null,
            materialSummary: null
        })
        var cache = [];
        let dataRefC = JSON.parse(JSON.stringify(dataRef, function (key, value) {
            if (typeof value === 'object' && value !== null) {
                if (cache.indexOf(value) !== -1) {
                    // Circular reference found, discard key
                    return;
                }
                // Store value in our collection
                cache.push(value);
            }
            return value;
        }))
        cache = null;
        
        if (eventType && eventType == "pileCrossSection") {
            await this.setState({
                mode: "add",
                situation: "pileCrossSection",
                nodeId: dataRefC.id,
              

            })
           
            this.setCrossDefault()
            
            
        } else if (eventType && eventType.includes("pileCrossSectionUnit")) {

            let res = await this.props.getCapReinforcementDetail({ id: dataRefC.id })
            if (res) {
                let { capReinforcement, materialSummary, reinforcementDetail, reinforcementDetailSummary, singleMaterialSummary,crossSectionTemplate } = res;
                const len = singleMaterialSummary?singleMaterialSummary.length:0;
                const len2 = materialSummary?materialSummary.length:0;
                for (let i = 0; i < len; i++) {
                    let item = singleMaterialSummary[i];
                    if (!item.mergeSize) {
                        if (i > 0 && singleMaterialSummary[i].type == singleMaterialSummary[i - 1].type) {
                            item.merged = true
                        }
                    }
                }
                for (let i = 0; i < len2; i++) {
                    let item = materialSummary[i];
                    if (!item.mergeSize) {
                        if (i > 0 && materialSummary[i].type == materialSummary[i - 1].type) {
                            item.merged = true
                        }
                    }
                }
                await this.setState({
                    mode: "edit",
                    situation: "pileCrossSection",
                    crossSectionTemplate,
                    updateTime: capReinforcement?new Date(capReinforcement.updateTime).toLocaleDateString():null,
                    tdata: reinforcementDetail,
                    detail: capReinforcement,
                    materialSummary,
                    reinforcementDetail,
                    reinforcementDetailSummary,
                    singleMaterialSummary
                })
                await this.setCrossDefault()
                if (this.state.formContext) {
                    this.state.formContext.setFormData({...capReinforcement})
                   
                }
               
            }

        } else if (eventType && eventType == "foundCrossSection") {
            await this.setState({
                mode: "add",
                situation: "foundCrossSection",
                nodeId: dataRefC.id,

            })
            this.setCrossDefault()
            
        } else if (eventType && eventType.includes("foundCrossSectionUnit")) {
            let res = await this.props.getCushionStoneDetail({ id: dataRefC.id })
            if (res) {
                let { capReinforcement, materialSummary, reinforcementDetail, reinforcementDetailSummary, singleMaterialSummary,crossSectionTemplate} = res;

                const len = singleMaterialSummary?singleMaterialSummary.length:0;
                const len2 = materialSummary?materialSummary.length:0;
                for (let i = 0; i < len; i++) {
                    let item = singleMaterialSummary[i];
                    if (!item.mergeSize) {
                        if (i > 0 && singleMaterialSummary[i].type == singleMaterialSummary[i - 1].type) {
                            item.merged = true
                        }
                    }
                }
                for (let i = 0; i < len2; i++) {
                    let item = materialSummary[i];
                    if (!item.mergeSize) {
                        if (i > 0 && materialSummary[i].type == materialSummary[i - 1].type) {
                            item.merged = true
                        }
                    }
                }
                await this.setState({
                    mode: "edit",
                    crossSectionTemplate,
                    situation: "foundCrossSection",
                    updateTime: capReinforcement?new Date(capReinforcement.updateTime).toLocaleDateString():null,
                    tdata: reinforcementDetail,
                    detail: capReinforcement,
                    materialSummary,
                    reinforcementDetail,
                    reinforcementDetailSummary,
                    singleMaterialSummary
                })
               await  this.setCrossDefault()
                if (this.state.formContext) {
                    this.state.formContext.setFormData(capReinforcement)
                }
                
                
            }

        } else if (eventType && eventType == "pileFoundCrossSection") {
            await this.setState({
                mode: "add",
                situation: "pileFoundCrossSection",
                nodeId: dataRefC.id,
 

            })
            this.setCrossDefault()
        } else if (eventType && eventType.includes("pileFoundCrossSectionUnit")) {
            let res = await this.props.getCapReinforcementDetail2({ id: dataRefC.id })
            if (res) {
                let { pileReinforcement, materialSummary, reinforcementDetail, reinforcementDetailSummary, singleMaterialSummary,crossSectionTemplate } = res;
                const len = singleMaterialSummary?singleMaterialSummary.length:0;
                const len2 = materialSummary?materialSummary.length:0;
                for (let i = 0; i < len; i++) {
                    let item = singleMaterialSummary[i];
                    if (!item.mergeSize) {
                        if (i > 0 && singleMaterialSummary[i].type == singleMaterialSummary[i - 1].type) {
                            item.merged = true
                        }
                    }
                }
                for (let i = 0; i < len2; i++) {
                    let item = materialSummary[i];
                    if (!item.mergeSize) {
                        if (i > 0 && materialSummary[i].type == materialSummary[i - 1].type) {
                            item.merged = true
                        }
                    }
                }
                await this.setState({
                    mode: "edit",
                    crossSectionTemplate,
                    situation: "pileFoundCrossSection",
                    updateTime: pileReinforcement?new Date(pileReinforcement.updateTime).toLocaleDateString():null,
                    tdata: reinforcementDetail,
                    detail: pileReinforcement,
                    materialSummary,
                    reinforcementDetail,
                    reinforcementDetailSummary,
                    singleMaterialSummary
                })
                await this.setCrossDefault()
                if (this.state.formContext) {
                    this.state.formContext.setFormData(pileReinforcement)
                }
               
            }
        }
        this.setState({
            loading: false
        })


    }
    updateTreeNode(key, list) {
        let data = this.state.tabs;
        let target = this.getTargetNodes(data, key)
        if (target) {
            target.children = list
        }
        this.setState({
            data: [...data]
        })
    }
    loadData(e) {

        return new Promise(async (resolve, reject) => {
            let { loadedKeys } = this.state;
            const { project } = this.props;
            let { eventKey, dataRef } = e.props
            if (!loadedKeys.includes(eventKey)) {
                loadedKeys.push(eventKey)
            }

            if (e.props.children && e.props.children.length) {
                resolve()
                return;
            }
            if (!dataRef) {
                dataRef = cloneDeep(e.props)
                dataRef.rg = true;
                delete dataRef.context
            }
            if (eventKey == "pileCrossSection") {
                let res = await this.props.capReinforcementList({ projectId: project.id })
                if (res && res.length) {
                    const len = res.length
                    for (let i = 0; i < len; i++) {
                        let item = res[i];
                        item.key = "pileCrossSectionUnit" + item.id;
                        item.title = "方案:" + item.configureName;

                        item.isLeaf = true
                        if (item.isLeaf) {
                            item.title = <span>{item.title}&nbsp;&nbsp;<Icon onClick={e => this.deleteNodeData(e, item)} type="delete" /></span>
                        }
                        // this.insertTreeNode('pileCrossSection', item)
                    }
                    dataRef.children = res
                }
                if (dataRef.rg) {
                    this.updateTreeNode(dataRef.eventKey, res)
                }

            } else if (eventKey == "foundCrossSection") {
                let res = await this.props.cushionStoneList({ projectId: project.id });
                if (res && res.length) {
                    const len = res.length
                    for (let i = 0; i < len; i++) {
                        let item = res[i];
                        item.key = "foundCrossSectionUnit" + item.id;
                        item.title = "方案:" + item.configureName;
                        item.isLeaf = true;
                        if (item.isLeaf) {
                            item.title = <span>{item.title}&nbsp;&nbsp;<Icon onClick={e => this.deleteNodeData(e, item)} type="delete" /></span>
                        }
                        // this.insertTreeNode('foundCrossSection', item)
                    }
                    dataRef.children = res
                }
                if (dataRef.rg) {
                    this.updateTreeNode(dataRef.eventKey, res)
                }
            } else if (eventKey == "pileFoundCrossSection") {
                let res = await this.props.pileReinforcementList({ projectId: project.id });
                if (res && res.length) {
                    const len = res.length
                    for (let i = 0; i < len; i++) {
                        let item = res[i];
                        item.key = "pileFoundCrossSectionUnit" + item.id;
                        item.title = "方案:" + item.configureName;
                        item.isLeaf = true;
                        if (item.isLeaf) {
                            item.title = <span>{item.title}&nbsp;&nbsp;<Icon onClick={e => this.deleteNodeData(e, item)} type="delete" /></span>
                        }
                        // this.insertTreeNode('foundCrossSection', item)
                    }
                    dataRef.children = res
                }
                if (dataRef.rg) {
                    this.updateTreeNode(dataRef.eventKey, res)
                }
            }

            this.setState({
                tabs: [...this.state.tabs]
            })
            resolve()
            // if(eventKey==){

            // }


        })
    }
    getGjsn(level){
        return level?<span className={'gjsn'+level}></span>:undefined
    }
    render() {
        const { loading, detail,crossSectionTemplate, updateTime, mode, situation, loadedKeys, expandedKeys, selectedKeys, tabs, tdata, reinforcementDetailSummary, singleMaterialSummary, materialSummary, modalContext } = this.state;

        const { project } = this.props;
        return (
            <div className="renforceBox">
                <div className="nav">
                    <button onClick={this.submit}>配筋计算</button> <button onClick={this.export}>配筋导出</button><span style={{marginLeft:"20px"}}>当前方案:{detail?detail.configureName:"---"}</span>
                </div>
                <div className="main">
                    <div className="left">
                        <div className="title">结构目录树</div>
                        <div style={{ padding: "10px 15px" }}>
                            <Tree onExpand={this.onExpand}
                                loadedKeys={loadedKeys}
                                expandedKeys={expandedKeys}
                                selectedKeys={selectedKeys}
                                loadData={(e) => this.loadData(e)}
                                treeData={tabs}
                                onSelect={this.onSelect}>
                                {tabs ? this.renderTreeNodes(tabs) : null}

                            </Tree>
                        </div>
                    </div>
                    <div style={loading ? { opacity: 0 } : { opacity: 1 }} className="center">
                        <div className="title"><div>配筋方案</div>
                            <div></div></div>
                        <div className="tableBox">
                            {
                                situation == "pileCrossSection" ? <PileCrossSection crossSectionTemplate={crossSectionTemplate} mode={mode} onLoaded={(context) => {
                                    this.setState({
                                        formContext: context
                                    })
                                }} modalContext={modalContext}></PileCrossSection> : undefined
                            }
                            {
                                situation == "foundCrossSection" ? <FoundCrossSection crossSectionTemplate={crossSectionTemplate} mode={mode} onLoaded={(context) => {
                                    this.setState({
                                        formContext: context
                                    })
                                }} modalContext={modalContext}></FoundCrossSection> : undefined
                            }
                            {
                                situation == "pileFoundCrossSection" ? <PileFoundCrossSection crossSectionTemplate={crossSectionTemplate} mode={mode} onLoaded={(context) => {
                                    this.setState({
                                        formContext: context
                                    })
                                }} modalContext={modalContext}></PileFoundCrossSection> : undefined
                            }
                        </div>
                    </div>
                    <div style={loading ? { opacity: 0 } : { opacity: 1 }} className="right">
                        <div className="title">材料统计</div>
                        <div className="extra">
                            <div>
                                <div>1.&nbsp;结构类型:&nbsp;{this.getNameBySitua() + '配筋'}</div>
                                <div>2.&nbsp;工程名称:&nbsp;{project ? project.name : ''}</div>
                                <div>3.&nbsp;创建时间:&nbsp;{updateTime ? updateTime : '---'}</div>
                            </div>
                        </div>
                        <div className="tableBox tableBox1">
                            <table style={{width:"97.33%",margin:"auto"}} className="hover">
                                <tbody>
                                    <tr className="title">
                                        <td className="tc" colSpan="8">单个{this.getNameBySitua()}钢筋明细表</td>
                                    </tr>
                                    <tr className="title">
                                        <td valign="middle" className="tc">编号</td>
                                        <td valign="middle" className="tc">直径(mm)</td>
                                        <td valign="middle" className="tc">大样</td>
                                        <td valign="middle" className="tc">单根长(cm)</td>
                                        <td valign="middle" className="tc">根数</td>
                                        <td valign="middle" className="tc">总长(m)</td>
                                        <td valign="middle" className="tc">单位重(kg/m)</td>
                                        <td valign="middle" className="tc">总量(kg)</td>
                                        {/* <td valign="middle" className="tc">小计</td> */}
                                    </tr>
                                    {
                                        tdata && tdata.length ? tdata.map((item, index) => {
                                            return <tr key={'t' + index}>
                                                <td>{item.no}</td>
                                                <td>
                                                    {
                                                        this.getGjsn(item.reinforcementGrade)
                                                    }
       
                                                    <span>{item.diameter}</span></td>
                                                <td>-</td>
                                                <td>{(item.length / 10).toFixed(1)}</td>
                                                <td>{item.number}</td>
                                                <td>{item.totalLength}</td>
                                                <td>{item.singleWeight}</td>
                                                <td>{item.totalWeight}</td>
                                                {/* <td></td> */}
                                            </tr>
                                        }) : <tr><td className="tc" colSpan="8">no data</td></tr>
                                    }
                                    {
                                        tdata && tdata.length ? <tr>
                                            <td >合计</td>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td>{reinforcementDetailSummary.number}</td>
                                            <td>{reinforcementDetailSummary.totalLength}</td>
                                            <td></td>
                                            <td>{reinforcementDetailSummary.totalWeight}</td>
                                            {/* <td valign="middle" className="tc">小计</td> */}
                                        </tr> : undefined
                                    }

                                </tbody>
                            </table>
                            <table style={{ marginTop: "20px",width:"48%" ,float:"left",marginLeft:"1.33%"}}>
                                <tbody>
                                    <tr className="title">
                                        <td className="tc" colSpan="5">单个{this.getNameBySitua()}材料数量小计</td>
                                    </tr>
                                    <tr className="title">
                                        <td valign="middle" className="tc">名称</td>
                                        <td valign="middle" className="tc">规格</td>
                                        <td valign="middle" className="tc">单位</td>
                                        <td valign="middle" className="tc">总量</td>
                                        <td valign="middle" className="tc">合计</td>
                                    </tr>
                                    {
                                        singleMaterialSummary && singleMaterialSummary.length ? singleMaterialSummary.map((item, index) => {
                                            return <tr key={'s' + index}>
                                                <td>{item.name}</td>
                                                <td>{item.type == 1 ? this.getGjsn(item.reinforcementGrade) : ''}<span>{item.standard}</span></td>
                                                <td>{item.unit}</td>
                                                <td>{item.total}</td>
                                                {
                                                    item.mergeSize ? <td rowSpan={item.mergeSize}>{item.summary || "-"}</td> : (item.merged ? undefined : <td rowSpan={item.mergeSize}>{item.summary || "-"}</td>)
                                                }

                                                {/* <td></td> */}
                                            </tr>
                                        }) : <tr><td className="tc" colSpan="5">no data</td></tr>
                                    }

                                </tbody>
                            </table>
                            <table style={{ marginTop: "20px",width:"48%",float:"left",marginLeft:"1.33%"}}>
                                <tbody>
                                    <tr className="title">
                                        <td className="tc" colSpan="5">{this.getNameBySitua()}材料数量表</td>
                                    </tr>
                                    <tr className="title">
                                        <td valign="middle" className="tc">名称</td>
                                        <td valign="middle" className="tc">规格</td>
                                        <td valign="middle" className="tc">单位</td>
                                        <td valign="middle" className="tc">总量</td>
                                        <td valign="middle" className="tc">合计</td>
                                    </tr>
                                    {
                                        materialSummary && materialSummary.length ? materialSummary.map((item, index) => {
                                            return <tr key={'m' + index}>
                                                <td>{item.name}</td>
                                                <td>{item.type == 1 ?this.getGjsn(item.reinforcementGrade) : ''}<span>{item.standard}</span></td>
                                                <td>{item.unit}</td>
                                                <td>{item.total}</td>
                                                {
                                                    item.mergeSize ? <td rowSpan={item.mergeSize}>{item.summary || "-"}</td> : (item.merged ? undefined : <td rowSpan={item.mergeSize}>{item.summary || "-"}</td>)
                                                }
                                                {/* <td></td> */}
                                            </tr>
                                        }) : <tr><td className="tc" colSpan="5">no data</td></tr>
                                    }
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <ToolConfigModals
                    onLoaded={context => {
                        this.setState({ modalContext: context })
                    }}
                />
            </div>
        )
    }
}
export default connect(
    ({ dict: { dictlist }, project: { current }, }) => ({ dictlist, project: current }),
    dispatch => ({
        addCapReinforcement: (values, onSuccess, onError) => dispatch({
            type: 'renforce/addCapReinforcement',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        addCushionStone: (values, onSuccess, onError) => dispatch({
            type: 'renforce/addCushionStone',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        addPileReinforcement: (values, onSuccess, onError) => dispatch({
            type: 'renforce/addPileReinforcement',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        deleteCapReinforcement: (values, onSuccess, onError) => dispatch({
            type: 'renforce/deleteCapReinforcement',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        exportCapReinforcement: (values, onSuccess, onError) => dispatch({
            type: 'renforce/exportCapReinforcement',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        deleteCushionStone: (values, onSuccess, onError) => dispatch({
            type: 'renforce/deleteCushionStone',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        deletePileReinforcement: (values, onSuccess, onError) => dispatch({
            type: 'renforce/deletePileReinforcement',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        updateCapReinforcement: (values, onSuccess, onError) => dispatch({
            type: 'renforce/updateCapReinforcement',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        updateCushionStone: (values, onSuccess, onError) => dispatch({
            type: 'renforce/updateCushionStone',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        updatePileReinforcement: (values, onSuccess, onError) => dispatch({
            type: 'renforce/updatePileReinforcement',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        capReinforcementList: (values) => dispatch({
            type: 'renforce/capReinforcementList',
            payload: values
        }),
        cushionStoneList: (values) => dispatch({
            type: 'renforce/cushionStoneList',
            payload: values
        }),
        pileReinforcementList: (values) => dispatch({
            type: 'renforce/pileReinforcementList',
            payload: values
        }),
        getCapReinforcementDetail: (values) => dispatch({
            type: 'renforce/getCapReinforcementDetail',
            payload: values
        }),
        getCushionStoneDetail: (values) => dispatch({
            type: 'renforce/getCushionStoneDetail',
            payload: values
        }),
        getCapReinforcementDetail2: (values) => dispatch({
            type: 'renforce/getCapReinforcementDetail2',
            payload: values
        }),
        crossTempList: (values) => dispatch({
            type: 'renforce/crossTempList',
            payload: values
        }),

    })
)(Renforce);